
using AutoMapper;
using DTO;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Model;
using SqlSugar;
using System.Linq.Expressions;
using Util;

namespace API.Controllers
{
    public class ShowCusController : BaseController
    {
        Repository<tShowCus> _ShowCus;
        Repository<tShowSign> _ShowSign;
        readonly IMapper _mapper;
        ISqlSugarClient _db;
        public ShowCusController(Repository<tShowCus> ShowCus, IMapper mapper, Repository<tShowSign> showSign, ISqlSugarClient db)
        {
            _ShowCus = ShowCus;
            _mapper = mapper;
            _ShowSign = showSign;
            _db = db;
        }

        /// <summary>
        /// 查询指定客户资料
        /// </summary>
        /// <param name="wxid"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<ResultMsg<ShowCusOutput>> GetRecordToday(string? wxid)
        {
            ResultMsg<ShowCusOutput> result= new ResultMsg<ShowCusOutput>();
            try
            {
                ShowCusOutput dao = new ShowCusOutput();
                if (string.IsNullOrEmpty(wxid))
                    return result.Bad();
                var cus = (await  _ShowCus.GetListAsync(t => t.FWXID.Equals(wxid))).FirstOrDefault();
                if (cus == null)
                    return result.Success();
                dao=_mapper.Map<ShowCusOutput>(cus);

                string now = DateTime.Now.ToString("yyyy-MM-dd");
                List<tShowSign> sign = await _ShowSign.GetListAsync(t => t.FShowCusID.Equals(dao.fId) && t.CreateTime.Equals(now));
                if (sign == null || sign.Count == 0)
                {
                    dao.fIsSign = false;
                }
                return result.Success(dao);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("ShowCusController--GetRecordToday:" + ex.Message);
                return result.Exception();
            }
        }

        /// <summary>
        /// 签到
        /// </summary>
        /// <param name="cus"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<ResultMsg<string>> SignIn([FromBody] SaveShowCusInput dto)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                if (dto == null)
                    return result.Bad();
                if (string.IsNullOrEmpty(dto.fName))
                    return result.Error("请问尊姓大名？");
                if (string.IsNullOrEmpty(dto.fTel))
                    return result.Error("靓仔，留个联系方式");

                string now = DateTime.Now.ToString("yyyy-MM-dd");
                var model = _mapper.Map<tShowCus>(dto);
                if (dto.fId == "0")
                    model.Id = "";
                InitEntity(model);
                await _ShowCus.InsertOrUpdateAsync(model);
                bool needAdd = true;
                List<tShowSign> sign = await  _ShowSign.GetListAsync(t => t.FShowCusID.Equals(model.Id) && t.CreateTime.Equals(now));
                if (sign != null && sign.Count > 0)
                {
                    needAdd = false;
                }
                if (needAdd)
                {
                    tShowSign showSign = new tShowSign();
                    showSign.FShowCusID = model.Id;
                    InitEntity(showSign);
                    await _ShowSign.InsertAsync(showSign);
                }
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error(ex.Message);
                return result.Exception();
            }
        }

        /// <summary>
        /// 签到统计
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<List<GetSignCountByDayOutput>>> GetSignCountByDay(GetSignCountByDayInput dto)
        {

            ResultMsg<List<GetSignCountByDayOutput>> result = new ResultMsg<List<GetSignCountByDayOutput>>();
            try
            {
                Expressionable<tShowSign> expressionable = Expressionable.Create<tShowSign>();//实例化Expressionable
                expressionable.And(sign => Convert.ToDateTime(sign.CreateTime) >= dto.start && Convert.ToDateTime(sign.CreateTime) <= dto.end);

                Expression<Func<tShowSign, bool>> expression = expressionable.ToExpression();//将Expressionable转为Expression

                dynamic d = await Task.Run(() => _db.Queryable<tShowSign>()
                   .Where(expression)
                   .GroupBy(sign => new {  sign.CreateTime.Date })
                   .Select(sign => new GetSignCountByDayOutput
                   {
                       CreateTime = sign.CreateTime.Date.ToString("yyyy-MM-dd"),
                       Count = SqlFunc.AggregateCount(sign.CreateTime)
                   }).OrderBy(sign => sign.CreateTime, OrderByType.Desc).ToList());

                return result.Success(d);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("ShowCusController--GetSignCountByDay:" + ex.Message);
                return result.Exception();
            }
        }

        /// <summary>
        /// 获取去指定日期签到明细数据
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<List<ShowCusOutput>>> GetSignByDay(string? date)
        {
            ResultMsg<List<ShowCusOutput>> result = new ResultMsg<List<ShowCusOutput>>();
            try
            {
                Expressionable<tShowSign, tShowCus> expressionable = Expressionable.Create<tShowSign, tShowCus>();//实例化Expressionable
                expressionable.And((sign, cus) => sign.CreateTime.Date.Equals(date));
                Expression<Func<tShowSign, tShowCus, bool>> expression = expressionable.ToExpression();//将Expressionable转为Expression

                dynamic d = await Task.Run(() => _db.Queryable<tShowSign, tShowCus>((sign, cus) => new object[] {
                    JoinType.Left,sign.FShowCusID == cus.Id
                })
                  .Where(expression).OrderBy(sign => sign.CreateTime, OrderByType.Desc)
                  .Select((sign, cus) => new ShowCusOutput
                  {
                      fId = cus.Id,
                      fAdr = cus.FAdr,
                      fCompany = cus.FCompany,
                      fName = cus.FName,
                      fTel = cus.FTel,
                      createTime = sign.CreateTime.ToString("yyyy-MM-dd")
                  }).ToList());
                return result.Success(d);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("ShowCusController--GetSignByDay:" + ex.Message);
                return result.Exception();
            }
        }

        /// <summary>
        /// 导出数据
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<dynamic>> GetSignByDayOut(DateTime start, DateTime end)
        {
            ResultMsg<dynamic> result = new ResultMsg<dynamic>();
            try
            {
                Expressionable<tShowSign, tShowCus> expressionable = Expressionable.Create<tShowSign, tShowCus>();//实例化Expressionable
                expressionable.And((sign, cus) => Convert.ToDateTime(sign.CreateTime) >= start && Convert.ToDateTime(sign.CreateTime) <= end);
                Expression<Func<tShowSign, tShowCus, bool>> expression = expressionable.ToExpression();//将Expressionable转为Expression

                dynamic d = await Task.Run(() => _db.Queryable<tShowSign, tShowCus>((sign, cus) => new object[] {
                    JoinType.Left,sign.FShowCusID == cus.Id
                })
                  .Where(expression).OrderBy(sign => sign.CreateTime, OrderByType.Desc)
                  .Select((sign, cus) => new
                  {
                      cus.Id,
                      cus.FAdr,
                      cus.FCompany,
                      cus.FName,
                      cus.FTel,
                      sign.CreateTime
                  }).ToList());
                return result.Success(d);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("ShowCusController--GetSignByDay:" + ex.Message);
                return result.Exception();
            }
        }
    }
}
